package swind.web.interceptor;


import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import swind.web.vo.TestVo;
import swind.web.vo.UserAnswerVo;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@SuppressWarnings({ "unused", "unchecked" })
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		System.out.println("LoginInterceptor--url:"+request.getRequestURL());
		// TODO Auto-generated method stub
		/*Date d1=new Date(request.getSession().getLastAccessedTime());
		Date now=new Date();
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("create time1:"+sf.format(d1));
		System.out.println("now:"+sf.format(now));
		
		Calendar cl=Calendar.getInstance();
		cl.setTime(d1);
		cl.add(Calendar.MINUTE, +1);
		if(cl.getTime().before(now)){
			System.out.println("cross session time");
			//登录超时，重新登录，默认1分钟方便测试
			request.getSession().removeAttribute("user");
			response.sendRedirect("/OnlineExam/login/index");
			return false;
		}*/
		
		if(request.getSession().getAttribute("user")==null){
			
			System.out.println("session TimeOut");
			response.sendRedirect("/OnlineExam/login/index");
			return false;
		}
		
		
		//测试有无过期试题
		/*Map<UserAnswerVo, List<TestVo>> userTestMap = (Map<UserAnswerVo, List<TestVo>>) request.getSession().getServletContext().getAttribute("userTestMap");
		if(userTestMap!=null){
			Iterator<UserAnswerVo> keyIt = userTestMap.keySet().iterator();
			while(keyIt.hasNext()){
				UserAnswerVo userAnswerVo=keyIt.next();
				Calendar cal =Calendar.getInstance();
				cal.setTime(userAnswerVo.getBeginTime());
				cal.add(Calendar.MINUTE, userAnswerVo.getExamTime());
				
				Calendar now =Calendar.getInstance();
				now.setTime(new Date());
				now.add(Calendar.MINUTE, 30);
				if(cal.getTime().before(now.getTime())){
					userTestMap.remove(userAnswerVo);
				}
			}
		}*/
		
		
		 
		return true;
	}
	
}
